Expand description
§Serde YML
§Seamless YAML Serialization for Rust.
§Overview
Serde YML
is a Rust library that simplifies YAML serialization and deserialization using Serde. Effortlessly convert Rust types to YAML and vice versa. Supports custom structs, enums, and error handling.
§Features
- Serialize Rust data structures to YAML format
- Deserialize YAML data into Rust types
- Support for custom structs and enums using Serde’s derive macros
- Handling of YAML’s
!tag
syntax for representing enum variants - Direct access to YAML values through the
Value
type and related types - Comprehensive error handling with
Error
,Location
, andResult
types - Well-documented with examples and explanations
Rust library for using the Serde serialization framework with data in Yaml file format.
§Rust Version Compatibility
This library is compatible with Rust 1.51.0 and above.
§Examples
§Serializing and Deserializing a HashMap
use std::collections::HashMap;
fn main() -> Result<(), serde_yml::Error> {
let mut map = HashMap::new();
map.insert("name".to_string(), &"John");
map.insert("age".to_string(), &"30");
let yaml = serde_yml::to_string(&map)?;
println!("Serialized YAML: {}", yaml);
let deserialized_map: HashMap<String, serde_yml::Value> = serde_yml::from_str(&yaml)?;
println!("Deserialized map: {:?}", deserialized_map);
Ok(())
}
§Serializing and Deserializing Custom Structs
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
struct Person {
name: String,
age: u32,
city: String,
}
fn main() -> Result<(), serde_yml::Error> {
let person = Person {
name: "Alice".to_string(),
age: 25,
city: "New York".to_string(),
};
let yaml = serde_yml::to_string(&person)?;
println!("Serialized YAML: {}", yaml);
let deserialized_person: Person = serde_yml::from_str(&yaml)?;
println!("Deserialized person: {:?}", deserialized_person);
Ok(())
}
§Using Serde derive
It can also be used with Serde’s derive macros to handle structs and enums defined in your program.
Structs serialize in the obvious way:
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Point {
x: f64,
y: f64,
}
fn main() -> Result<(), serde_yml::Error> {
let point = Point { x: 1.0, y: 2.0 };
let yaml = serde_yml::to_string(&point)?;
assert_eq!(yaml, "x: 1.0\n'y': 2.0\n");
let deserialized_point: Point = serde_yml::from_str(&yaml)?;
assert_eq!(point, deserialized_point);
Ok(())
}
Enums serialize using YAML’s !tag
syntax to identify the variant name.
use serde_derive::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, PartialEq, Debug)]
enum Enum {
Unit,
Newtype(usize),
Tuple(usize, usize, usize),
Struct { x: f64, y: f64 },
}
fn main() -> Result<(), serde_yml::Error> {
let yaml = "
- !Newtype 1
- !Tuple [0, 0, 0]
- !Struct {x: 1.0, y: 2.0}
";
let values: Vec<Enum> = serde_yml::from_str(yaml).unwrap();
assert_eq!(values[0], Enum::Newtype(1));
assert_eq!(values[1], Enum::Tuple(0, 0, 0));
assert_eq!(values[2], Enum::Struct { x: 1.0, y: 2.0 });
// The last two in YAML's block style instead:
let yaml = "
- !Tuple
- 0
- 0
- 0
- !Struct
x: 1.0
'y': 2.0
";
let values: Vec<Enum> = serde_yml::from_str(yaml).unwrap();
assert_eq!(values[0], Enum::Tuple(0, 0, 0));
assert_eq!(values[1], Enum::Struct { x: 1.0, y: 2.0 });
// Variants with no data can be written using !Tag or just the string name.
let yaml = "
- Unit # serialization produces this one
- !Unit
";
let values: Vec<Enum> = serde_yml::from_str(yaml).unwrap();
assert_eq!(values[0], Enum::Unit);
assert_eq!(values[1], Enum::Unit);
Ok(())
}
§Best Practices and Common Pitfalls
- When serializing large datasets, consider using
serde_yml::to_writer
to write the YAML output directly to a file or a writer instead of keeping the entire serialized string in memory. - Be cautious when deserializing untrusted YAML input, as it may contain unexpected or malicious data. Always validate and handle the deserialized data appropriately.
- When working with custom structs or enums, ensure that they implement the necessary Serde traits (
Serialize
andDeserialize
) for proper serialization and deserialization. - If you encounter any issues or have questions, refer to the library’s documentation and examples for guidance. If the problem persists, consider opening an issue on the library’s GitHub repository.
Re-exports§
pub use crate::de::from_reader;
pub use crate::de::from_slice;
pub use crate::de::from_str;
pub use crate::de::Deserializer;
pub use crate::modules::error::Error;
pub use crate::modules::error::Location;
pub use crate::modules::error::Result;
Modules§
- The
de
module contains the library’s YAML deserializer. - The
generators
module contains functions for generating data. - The
libyml
module contains the library’s YAML parser and emitter. - The
loader
module contains theLoader
type for YAML loading. - The
macros
module contains functions for generating macros. - The
mapping
module contains theMapping
type for YAML mappings. A YAML mapping and its iterator types. - The
models
module contains the data models for the library. - The
modules
module contains the library’s modules. - The
utilities
module contains utility functions for the library. - The
value
module contains theValue
type for YAML values. The Value enum, a loosely typed way of representing any valid YAML value. - The
with
module contains theWith
type for YAML values. Customizations to use with Serde’s#[serde(with = …)]
attribute.
Macros§
- Macro
from_number
to implement conversion from number types toValue
. - Macro to simplify the match logic for file generation.
- A macro for generating ASCII art from text.
macro_check_directory
Macromacro_cleanup_directories
Macromacro_create_directories
Macro- Macro to generate a function that retrieves a field value from a JSON file.
- Custom logging macro for various log levels and formats.
- Replaces placeholders in a given line with corresponding values from the provided parameters.
- A macro that generates implementations of the
PartialEq
trait for primitive numeric types andValue
based on the specified conversion method and base type.
Structs§
- A YAML mapping in which the keys and values are both
serde_yml::Value
. - Represents a YAML number, whether integer or floating point.
- A structure for serializing Rust values into YAML.
Enums§
- Represents any valid YAML value.
Traits§
- A type that can be used to index into a
serde_yml::Value
. See theget
andget_mut
methods ofValue
.
Functions§
- Interpret a
serde_yml::Value
as an instance of typeT
. - Run the Serde YML tool.
- Serialize the given data structure as a String of YAML.
- Converts a serializable value into a
serde_yml::Value
. - Serialize the given data structure as YAML into the IO stream.
Type Aliases§
- A YAML sequence in which the elements are
serde_yml::Value
.